<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Oauth extends CI_Controller {

    private   $TB ;
    private   $tb_akey ;
    private   $tb_skey ;


    public function __construct() {

        parent::__construct();
        $this->load->library('Taobao/TopSdk') ;
        $this->TB = new TopClient;
        $this->TB->appkey = $this->config->item('tb_akey');
        $this->TB->secretKey = $this->config->item('tb_skey');
        $this->tb_akey = $this->config->item('tb_akey');
        $this->tb_skey = $this->config->item('tb_skey');
    }




    public function tb_oauth()
    {

          $url = 'https://oauth.taobao.com/authorize';
          $params = array(
            'response_type'=>'code',
            'client_id'=>$this->tb_akey,
            'redirect_uri'=>site_url('oauth/tb_callback')
        );
        $params_string = http_build_query($params);
        redirect($url.'?'.$params_string);
    }

    public function tb_callback()
    {
         $url = 'https://oauth.taobao.com/token';
         $postfields= array(
            'grant_type'=>'authorization_code',
            'client_id'=>$this->tb_akey,
            'client_secret'=>$this->tb_skey,
            'code'=>$this->input->get_post('code'),
            'redirect_uri'=>site_url('taobao/callback')
        );
        $token = json_decode($this->TB->curl($url,$postfields));
        if(isset($token)&&!empty($token))
        {
                $user_info = $this->tb_user_info($token->access_token);
                $this->session->sess_expiration = $token->expires_in;
                $this->session->set_userdata('token',$token->access_token);
                $this->session->set_userdata('taobao_user_id',$token->taobao_user_id);
                $this->session->set_userdata('tb_is_login',1);
                $this->session->set_userdata('tb_nick',$user_info['nick']);
        }
        redirect('admin/index') ;
    }



    public function tb_user_info($token)
    {
        $req = new UserSellerGetRequest;
        $req->setFields("nick,sex");
        $resp = _object_array($this->TB->execute($req,$token));
         if(isset($resp['user'])&&!empty($resp['user']))
        {
            return   $resp['user'] ;
        }
        return false;
    }








}